<?php
/*********************************************
  CPG Dragonfly™ CMS
  ********************************************
  Copyright © 2004 - 2005 by CPG-Nuke Dev Team
  http://www.dragonflycms.com

  Dragonfly is released under the terms and conditions
  of the GNU GPL version 2 or any later version
**********************************************/
if (!defined('CPG_NUKE')) { exit; }

function edituser(Dragonfly_Identity $userinfo)
{
	$K = Dragonfly::getKernel();
	$db = $K->SQL;

	$mode = isset($_GET['edit']) ? $_GET['edit'] : 'profile';
	if ($mode == 'admin' && !defined('ADMIN_PAGES')) $mode = 'profile';
	if ($mode == 'reg_details') {
		Dragonfly_Page::setTitle('. '._BC_DELIM.' '._MA_REGISTRATION_INFO);
	} elseif ($mode == 'profile') {
		$section = 'section=1 OR section=2';
		Dragonfly_Page::setTitle('. '._BC_DELIM.' '._MA_PROFILE_INFO);
	} elseif ($mode == 'private') {
		$section = 'section=3';
		Dragonfly_Page::setTitle('. '._BC_DELIM.' '._MA_PRIVATE);
	} elseif ($mode == 'prefs') {
		$section = 'section=5';
		Dragonfly_Page::setTitle('. '._BC_DELIM.' '._MA_PREFERENCES);
	} elseif ($mode == 'avatar') {
		Dragonfly_Page::setTitle('. '._BC_DELIM.' '._AVATAR_CONTROL);
	} else {
		if (!defined('ADMIN_PAGES')) URL::redirect(URL::index('Your_Account'));
	}

	if (!defined('ADMIN_PAGES')) {
		$block = array(
			'bid' => 10000,
			'view' => 1,
			'side' => 'l',
			'title' => _TB_BLOCK,
			'content' => member_block()
		);
		Blocks::custom($block);
		$block = NULL;
		require_once('header.php');
		$action = URL::index();
	} else {
		echo "<strong>{$userinfo->username}</strong>";
		if ($userinfo->level == 0) { echo ' ('._ACCTSUSPEND.')'; }
		elseif ($userinfo->level < 0) { echo ' ('._ACCTDELETE.')'; }
		echo '<br />
		'.(($mode == 'profile') ? '<strong>'._MA_PROFILE_INFO.'</strong>' : '<a href="'.URL::admin('users&amp;mode=edit&amp;edit=profile&amp;id='.$userinfo->id).'">'._MA_PROFILE_INFO.'</a>').' |
		'.(($mode == 'reg_details') ? '<strong>'._MA_REGISTRATION_INFO.'</strong>' : '<a href="'.URL::admin('users&amp;mode=edit&amp;edit=reg_details&amp;id='.$userinfo->id).'">'._MA_REGISTRATION_INFO.'</a>').' |
		'.(($mode == 'avatar') ? '<strong>'._AVATAR_CONTROL.'</strong>' : '<a href="'.URL::admin('users&amp;mode=edit&amp;edit=avatar&amp;id='.$userinfo->id).'">'._AVATAR_CONTROL.'</a>').' |
		'.(($mode == 'admin') ? '<strong>'._MA_PRIVILEGES.'</strong>' : '<a href="'.URL::admin('users&amp;mode=edit&amp;edit=admin&amp;id='.$userinfo->id).'">'._MA_PRIVILEGES.'</a>').'
		<br /><br />';
		$action = URL::admin('users&amp;id='.$userinfo->id);
	}

	if (!empty($userinfo->website) && false === strpos($userinfo->website, '://')) {
		$userinfo->website = "http://{$userinfo->website}";
	}

	$K->CFG->avatar->allow_upload = (ini_get('file_uploads') == '0' || strtolower(ini_get('file_uploads') == 'off')) ? false : $K->CFG->avatar->allow_upload;

	switch ($mode)
	{
	case 'reg_details':
		$TPL = $K->OUT;
		$TPL->userinfo = $userinfo;
		$TPL->display('Your_Account/edit/reg_details');
		return;

	case 'avatar':
		if (isset($_POST['submitavatar']) && isset($_POST['avatarselect'])) {
			$user_avatar = $_POST['avatarselect'];
			$user_avatar_type = 3;
		} else {
			$user_avatar = $userinfo->avatar;
			$user_avatar_type = $userinfo->avatar_type;
		}
		if (1 == $user_avatar_type) {
			$avatar = $K->CFG->avatar->path . '/' .$user_avatar;
		} else if (2 == $user_avatar_type) {
			$avatar = $user_avatar;
		} else if (3 == $user_avatar_type) {
			$avatar = $K->CFG->avatar->gallery_path . '/' .$user_avatar;
		} else {
			$avatar = $K->CFG->avatar->gallery_path . '/' .$K->CFG->avatar->default;
		}

		$TPL = $K->OUT;
		$TPL->avatar_img  = $avatar;
		$TPL->avatar_type = $user_avatar_type;
		$TPL->user_avatar = $user_avatar;
		$TPL->display('Your_Account/edit/avatar');
		return;

	case 'admin':
		$result = $db->query("SELECT * FROM {$db->TBL->bbranks} WHERE rank_special = 1 ORDER BY rank_title");
		$rank_select = array(array(
			'value' => 0,
			'title' => 'No special rank assigned',
		));
		while ($row = $result->fetch_assoc()) {
			$rank_select[] = array(
			'value'   => $row['rank_id'],
			'title'   => $row['rank_title'],
			'current' => $row['rank_id'] == $userinfo->rank,
			);
		}

		$TPL = $K->OUT;
		$TPL->ranks    = $rank_select;
		$TPL->userinfo = $userinfo;
		$TPL->display('Your_Account/edit/admin');
		return;
	}

	$fields = array();
	$result = $db->query("SELECT * FROM {$db->TBL->users_fields} WHERE {$section} ORDER BY section, fid");
	if ($result->num_rows > 0) {
//		echo '<tr><td class="row1" colspan="2">'._MA_ITEMS_REQUIRED."</td></tr>\n";
		while ($row = $result->fetch_assoc())
		{
			$field = ma_tpl_field($row, $userinfo);
			if ($field) $fields[] = $field;
		}
	}

	$TPL = $K->OUT;
	$TPL->userinfo = $userinfo;
	$TPL->user_section_fields = $fields;
	$TPL->display('Your_Account/edit/section');
}

function saveuser(Dragonfly_Identity $userinfo)
{
	global $CPG_SESS;

	$K = Dragonfly::getKernel();
	$db = $K->SQL;

	$mode = isset($_GET['edit']) ? $_GET['edit'] : 'profile';
	$mode = isset($_POST['save']) ? $_POST['save'] : $mode;
	if ($mode == 'admin' && !defined('ADMIN_PAGES')) $mode = 'profile';
	if ($mode == 'profile') {
		$section = 'section=1 OR section=2';
	} elseif ($mode == 'private') {
		$section = 'section=3';
	} elseif ($mode == 'prefs') {
		$section = 'section=5';
	}

	if ($mode == 'reg_details')
	{
		if (isset($_POST['new_password'])) {
			$new_password = $_POST['new_password'];
			if ($new_password != '') {
				$verify_password = isset($_POST['verify_password']) ? $_POST['verify_password'] : '';
				if ($new_password != $verify_password) {
					cpg_error(_PASSDIFFERENT, 'ERROR: Password mismatch');
				}
				if (strlen($new_password) < $K->CFG->member->minpass) {
					cpg_error(_YOUPASSMUSTBE.' <b>'.$K->CFG->member->minpass.'</b> '._CHARLONG, 'ERROR: Password too short');
				}
				$ID = Dragonfly::getKernel()->IDENTITY;
				if (defined('ADMIN_PAGES')) {
					$ID = $userinfo;
				} else {
					$provider = \Poodle\Auth\Provider::getById(1);
					if (!$provider->isValidPassword($ID->id, $_POST['current_password'])) {
						cpg_error('Password incorrect');
					}
				}
				$ID->updateAuth(1, $ID->nickname, $new_password);
			}
		}
		$user_email = isset($_POST['user_email']) ? $_POST['user_email'] : $userinfo->email;
		if (($K->CFG->member->allowmailchange || defined('ADMIN_PAGES')) && $user_email != $userinfo->email) {
			if (!defined('ADMIN_PAGES')) {
				$ID = Dragonfly::getKernel()->IDENTITY;
				$provider = \Poodle\Auth\Provider::getById(1);
				if (!$provider->isValidPassword($ID->id, $_POST['current_password'])) {
					cpg_error('Password incorrect');
				}
			}
			if (is_email($user_email) < 1) {
				cpg_error(_ERRORINVEMAIL);
			}
			$userinfo->email = $user_email;
		}
		if (defined('ADMIN_PAGES') && isset($_POST['username']) && $_POST['username'] != $userinfo['username']) {
			if (preg_match('#(\ |\*|#|\\\|%|"|\'|`|&|\^|@)', $_POST['username'])) { cpg_error(_ERRORINVNICK); }
			global $user_prefix;
			if ($db->sql_count($user_prefix.'_users u, '.$user_prefix.'_users_temp t', "u.username='$_POST[username]' OR t.username='$_POST[username]' LIMIT 1") > 0) {
				cpg_error(_NICKTAKEN);
			}
			$userinfo->nickname = $_POST['username'];
		}
	}

	elseif ($mode == 'avatar')
	{
		if (isset($_POST['submitavatar']))
		{
			return edituser($userinfo);
		}

		$AVATAR_CFG = $K->CFG->avatar;

		require_once('modules/'.basename(dirname(__FILE__)).'/avatars.php');
		// Local avatar?
		$avatar_local = isset($_POST['user_avatar']) ? $_POST['user_avatar'] : '';
		// Remote avatar?
		$avatar_remoteurl = !empty($_POST['avatarremoteurl']) ? htmlprepare($_POST['avatarremoteurl']) : '';
		// Upload avatar thru remote or upload?
		$avatar_upload = !empty($_POST['avatarurl']) ? trim($_POST['avatarurl']) : (!empty($_FILES['avatar']) && ($_FILES['avatar']['tmp_name'] != "none") ? $_FILES['avatar']['tmp_name'] : '');
		$avatar_name = !empty($_FILES['avatar']['name']) ? $_FILES['avatar']['name'] : '';

		// 0 = USER_AVATAR_NONE
		if (isset($_POST['avatardel']) || $avatar_local == '')
		{
			avatar_delete($userinfo);
		}
		// 1 = USER_AVATAR_UPLOAD
		if ((!empty($avatar_upload) || !empty($avatar_name)) && $AVATAR_CFG->allow_upload)
		{
			if (!empty($avatar_upload)) {
				avatar_upload(empty($avatar_name), $userinfo, $avatar_upload, $_FILES['avatar']);
			} elseif (!empty($avatar_name)) {
				cpg_error(sprintf(_AVATAR_FILESIZE, round($AVATAR_CFG->filesize / 1024)), 'ERROR: Filesize');
			}
		}
		// 2 = USER_AVATAR_REMOTE
		else if ($avatar_remoteurl != $userinfo->avatar && $avatar_remoteurl != '' && $AVATAR_CFG->allow_remote)
		{
			if (!preg_match('#^(http)|(ftp):\/\/#i', $avatar_remoteurl) ) {
				$avatar_remoteurl = 'http://' . $avatar_remoteurl;
			}
			if (preg_match('#^((http)|(ftp):\/\/[\w\-]+?\.([\w\-]+\.)+[\w]+(:[0-9]+)*\/.*?\.(gif|jpg|jpeg|png)$)#is', $avatar_remoteurl) ) {
				if ((in_array ('getimagesize', explode(',', ini_get ('disable_functions')))) || (ini_get ('disable_functions') =='getimagesize')) {
					cpg_error('getimagesize is disabled', _AVATAR_ERR_URL);
				} elseif ((!getimagesize($avatar_remoteurl)) ){
					cpg_error('Image has wrong filetype', _AVATAR_ERR_URL);
				} elseif (!($file_data = get_fileinfo($avatar_remoteurl, !$AVATAR_CFG->animated))) {
					cpg_error(_AVATAR_ERR_URL);
				} elseif ($file_data['size'] > $AVATAR_CFG->filesize) {
					cpg_error(sprintf(_AVATAR_FILESIZE, round($AVATAR_CFG->filesize / 1024)));
				} elseif (!$AVATAR_CFG->animated && $file_data['animation']) {
					cpg_error('Animated avatar not allowed');
				}
				if (avatar_size($avatar_remoteurl)) {
					avatar_delete($userinfo);
					$userinfo->avatar      = $avatar_remoteurl;
					$userinfo->avatar_type = 2;
				}
			} else {
				cpg_error('Image has wrong filetype', 'ERROR: Image filetype');
			}
		}
		// 3 = USER_AVATAR_GALLERY
		else if ($avatar_local != $userinfo->avatar && $avatar_local != '' &&
		        $AVATAR_CFG->allow_local && file_exists($AVATAR_CFG->gallery_path.'/'.$avatar_local))
		{
			avatar_delete($userinfo);
			$userinfo->avatar      = $avatar_local;
			$userinfo->avatar_type = 3;
		}
	}

	elseif ($mode == 'admin') {
		$userinfo->allow_pm    = intval($_POST['user_allow_pm']);
		$userinfo->allowavatar = intval($_POST['user_allowavatar']);
		$userinfo->rank        = intval($_POST['user_rank']);
		//$deleteUserData        = isset($_POST['delete_user_data'] && $_POST['delete_user_data']) ? 1 : 0;
		$suspendreason = isset($_POST['suspendreason']) ? $_POST['suspendreason'] : 'no reason';
		if ($_POST['suspendreason'] != $userinfo['susdel_reason']) {
			$userinfo->susdel_reason = intval($suspendreason);
		}
		if (intval($_POST['user_suspend']) == 0 && $userinfo->level == 0) {
			$userinfo->level = 1;
		} elseif (intval($_POST['user_suspend']) > 0 && $userinfo->level > 0) {
			$message = _SORRYTO.' '.$K->CFG->global->sitename.' '._HASSUSPEND;
			if ($suspendreason > '') {
				$message .= "\n\n"._SUSPENDREASON."\n$suspendreason";
			}
			$from = 'noreply@'.str_replace('www.', '', $K->CFG->server->domain);
			if (!send_mail($mailer_message, $message, 0, _ACCTSUSPEND, $userinfo->email, $userinfo['username'], $from)) {
				trigger_error($mailer_message, E_USER_WARNING);
			}
			$userinfo->level = 0;
			$userinfo->susdel_reason = $suspendreason;
			//if ($deleteUserData) \Poodle\Events trigger_event('deleteUserData', array('nickname' => $userinfo->nickname));
		}
	}

	else {
		$result = $db->query("SELECT field, type FROM {$db->TBL->users_fields} WHERE ".$section);
		if ($result->num_rows > 0) {
			while ($row = $result->fetch_assoc()) {
				$field = ($row['field'] == 'name')?'realname':$row['field'];
				$value = Fix_Quotes($_POST[$field],1);
				if ($row['field'] == 'user_lang' && !$K->CFG->global->multilingual) continue;
				if ($row['type'] == 1 || $row['type'] == 4) {
					$value = intval($value);
				} else {
					if ($field == 'user_website') {
						if (!preg_match('#^http[s]?:\/\/#i', $value)) {
							$value = 'http://' . $value;
						}
						if (!preg_match('#^(http[s]?\:\/\/)?([a-z0-9\-\.]+)?[a-z0-9\-]+\.[a-z]{2,4}$#i', $value)) {
							$value = '';
						}
					}
				}
				if ($row['type'] == 7 && !$K->CFG->member->allowusertheme) {
					$value = $K->CFG->global->Default_Theme;
				}
				if ($row['type'] == 6) {
					$value = date_raw($value);
					if (checkdate(substr($value, 4, 2), substr($value, 6, 2), substr($value, 0, 4))) {
						$userinfo[$row['field']] = $value;
					}
				} else {
					$userinfo[$row['field']] = $value;
				}
			}
		}
	}

	$userinfo->save();
	if (!defined('ADMIN_PAGES')) {
		if (isset($_POST['theme']) && $K->CFG->member->allowusertheme) {
			$CPG_SESS['theme'] = $_POST['theme'];
			unset($CPG_SESS['prevtheme']);
		}
		cpg_error(_TASK_COMPLETED, _TB_INFO, URL::index('&edit='.$mode));
	} else {
		cpg_error(_TASK_COMPLETED, _TB_INFO, URL::admin('users&mode=edit&edit='.$mode.'&id='.$userinfo->id));
		cpg_error(_TASK_COMPLETED, _TB_INFO, URL::admin('users&edit='.$userinfo->id));
	}
}
